﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using cndp.Model;

namespace cndp.View
{
    public partial class FormEditContest : Form
    {
        public BindingList<Contest> ContestList = new BindingList<Contest>();
        public string OldValue;

        public FormEditContest()
        {
            InitializeComponent();
        }

        private void FormEditContest_Load(object sender, EventArgs e)
        {
            KeyPreview = true;
        }

        private void dataGridViewChangeContestList_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            OldValue = dataGridViewChangeContestList[e.ColumnIndex, e.RowIndex].Value.ToString();
        }

        private void dataGridViewChangeContestList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var d = new Datacheck();
            var row = dataGridViewChangeContestList[e.ColumnIndex, e.RowIndex];
            if (row.ColumnIndex == 0)
            {
                if (d.CheckIfContainNumbers(row.Value.ToString()))
                {
                    MessageBox.Show(@"Fel format.", @"Ogiltigt data.");
                    row.Value = OldValue;
                }
            }
            if (row.ColumnIndex == 1)
            {
                if (!d.CheckIfInteger(row.Value.ToString()))
                {
                    MessageBox.Show(@"Fel format.", @"Ogiltigt data.");
                    row.Value = OldValue;
                }
                var idNotTaken = true;
                for (var i = 0; i < ContestList.Count; ++i)
                {
                    if (Convert.ToInt32(row.Value) == ContestList[i].Id && (i != row.RowIndex))
                    {
                        idNotTaken = false;
                    }
                }
                if (!idNotTaken)
                {
                    MessageBox.Show(@"Tävlings-ID redan taget", @"Ogiltigt data");
                    row.Value = OldValue;
                }
            }

            if (row.ColumnIndex == 3 || row.ColumnIndex == 4 || row.ColumnIndex == 5)
            {
                if (!d.CheckIfDateAndTime(row.Value.ToString()))
                {
                    MessageBox.Show(@"Fel format.", @"Ogiltigt data.");
                    row.Value = OldValue;
                }
            }
        }

        private void FormEditContest_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                Close();
        }
    }
}